package com.yidian.controller.upload;

import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author whb
 * @create 2021-05-13 9:01
 * @description 文件上传控制器
 */
@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OSSClient ossClient;

    /**
     * 本地上传
     * @param file
     * @return
     */
    @PostMapping("/native")
    public String nativeUpload(@RequestParam("file") MultipartFile file){
        String path = request.getSession().getServletContext().getRealPath("images");
        String filePath=path+"/"+file.getOriginalFilename();
        File desFile = new File(filePath);
        if (!desFile.exists()){
            desFile.mkdirs();
        }
        try {
            file.transferTo(desFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "http://localhost:9101/images/"+file.getOriginalFilename();
    }

    /**
     * 阿里云OSS存储
     * @param file
     * @return
     */
    @PostMapping("/oss")
    public String ossUpload(@RequestParam("file") MultipartFile file,String folder){
        String bucketName="yidianshop";
        String fileName=folder +"/" + UUID.randomUUID()+"-"+file.getOriginalFilename();
        try {
            ossClient.putObject(bucketName,fileName,file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "https://"+bucketName+".oss-cn-beijing.aliyuncs.com/"+fileName;
    }
}
